import * as React from "react";
import { observer } from "mobx-react";
import { Table, Input, Select, Button, Modal, Space } from "antd";

import {
  getresultsquery,
  getorderselect,
  getassignment,
} from "../../../deviceseversapi";

import "./index.less";

import "./index.less";
const { Option } = Select;
export enum dateEnum {
  "date" = "date",
  "time" = "time",
  "month" = "month",
  "year" = "year",
}
export interface MenuTableProps {}

export interface MenuTableState {
  type: Number;
  time: "date" | "time" | "month" | "year" | "week" | "quarter";
  loading: boolean;

  visible: boolean;
  binding: boolean;
  datalist: number[];
  status: string;
  id: string;
  conditionname: string;
  conditioncommand: string;
  addtitle: string;
  batch: string;
  condition: string;
  // id:number[];
  addedit: number;
  protocollist: number[];
  page: number;
  size: number;
  total: number;
  // isModalVisible:Boolean;
  // setIsModalVisible:Boolean;
  assignmentlist: any;
}

interface provinceClass {
  name: string;
  id: number;
  value: string;
}
@observer
class Consequence extends React.Component<MenuTableProps, MenuTableState> {
  state = {
    type: 1,
    time: dateEnum.date,
    loading: false,
    isModalVisible: false,
    visible: false,
    binding: false,
    addtitle: "新增",
    batch: "删除终端设备信息",
    terminallist: {},
    id: "",
    datalist: [],
    status: "全部", //0、新增 1、正在执行 2、执行成功 3、执行失败 4、等侍平台返回
    conditioncommand: "",
    conditionname: "",
    condition: "", //新增协议默认内容  编辑协议文本
    assignmentlist: [],
    protocollist: [],
    page: 1,
    size: 10,
    total: 0,
    // id:0,
    addedit: 1, //1新增或者2编辑
  };
  private columns = [
    {
      key: "isStatus",
      title: "状态",
      dataIndex: "isStatus",
      width: 100,
      render: (text, record) => {
        let isLoad = "";
        if (record.isStatus === "2") {
          isLoad = '<span class="are_loading">执行成功</span>';
        } else if (record.isStatus === "3") {
          isLoad = '<span class="no_loading">执行失败</span>';
        } else if (record.isStatus === "0") {
          isLoad = '<span class="no_loading">未执行</span>';
        } else if (record.isStatus === "1") {
          isLoad = '<span class="no_loading">正在执行</span>';
        } else if (record.isStatus === "4") {
          isLoad = '<span class="no_loading">等侍平台返回</span>';
        } else {
          isLoad = '<span class="no_loading">其它</span>';
        }
        return <div dangerouslySetInnerHTML={{ __html: isLoad }} />;
      },
    },
    {
      key: "commandName",
      title: "命令名称",
      dataIndex: "commandName",
      width: 150,
    },
    {
      key: "terminalName",
      title: "终端名称",
      dataIndex: "terminalName",
      width: "15%",
    },
    {
      key: "terminalAddress",
      title: "终端地址",
      dataIndex: "terminalAddress",
      width: "12%",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      width: "10%",
    },
    {
      key: "completionTime",
      title: "完成时间",
      dataIndex: "completionTime",
      width: "10%",
    },
    {
      key: "result",
      title: "结果",
      dataIndex: "result",
      ellipsis: true,
    },
    {
      title: "操作",
      key: "address",
      width: 80,
      render: (text, record) => {
        if (
          record.isStatus === "2" &&
          record.result &&
          record.result.indexOf("@") > 0 &&
          record.commandKey === "get_param"
        ) {
          return (
            <Space size="middle">
              <Button
                type="text"
                className="assignment"
                onClick={(event) => {
                  this.setState(
                    {
                      visible: true,
                      addtitle: "详情",
                      id: record.id,
                    },
                    () => {
                      this.assignment();
                    }
                  );
                }}
              >
                详情
              </Button>
            </Space>
          );
        }
      },
    },
  ];

  private resultColumns = [
    {
      title: "设备地址",
      dataIndex: "deviceAddr",
      width: 120,
      ellipsis: true,
    },
    {
      title: "设备名称",
      dataIndex: "deviceName",
      width: 150,
      ellipsis: true,
    },
    {
      title: "返回结果【终端,本地】",
      dataIndex: "localParam",
      ellipsis: true,
    },
  ];
  componentDidMount() {
    this.fetchget();
    this.agreement();
  }

  render() {
    const handleOk = () => {
      this.setState({
        visible: false,
      });
    };
    const handleCancel = () => {
      this.setState({
        visible: false,
      });
    };

    //绑定 解绑 删除后根据条件调用接口
    const bindingOk = () => {
      this.setState({
        binding: false,
      });
    };

    const bindingCancel = () => {
      this.setState({
        binding: false,
      });
    };

    // const { loading, selectedRowKeys } = this.state;

    //表格复选框
    let that = this;
    let pagination = {
      total: this.state.total,
      defaultCurrent: this.state.page,
      pageSize: this.state.size,
      showSizeChanger: true,
      onShowSizeChange: (current, pageSize) => {},
      onChange: (current, pageSize) => {
        that.setState(
          {
            page: current,
          },
          () => {
            this.fetchget();
          }
        );
      },
    };
    return (
      <>
        <div className="Consequence">
          <div className="rowcon_body">
            <div className="querystat">
              终端名称：
              <Input
                className="input"
                placeholder="请输入终端名称"
                value={this.state.conditionname}
                onChange={(event) => {
                  this.namechange(event);
                }}
              />
            </div>
            <div className="query">
              命令名称：
              <Select
                defaultValue={this.state.conditioncommand}
                className="searchselect"
                onChange={(event) => {
                  this.commandchange(event);
                }}
              >
                {this.state.protocollist.map((province: provinceClass) => (
                  <Option key={province.value} value={province.value}>
                    {province.name}
                  </Option>
                ))}
              </Select>
            </div>

            <div className="query">
              <Button
                type="primary"
                onClick={() => {
                  this.fetchget();
                }}
              >
                查询
              </Button>
            </div>
          </div>
          <div className="subject">
            <div className="operation"></div>
            <div>
              <Table
                columns={this.columns}
                dataSource={this.state.datalist}
                pagination={pagination}
              />
            </div>
          </div>
          <div>
            {/* 新增或者编辑弹窗 */}
            <Modal
              title={this.state.addtitle}
              visible={this.state.visible}
              onOk={handleOk}
              onCancel={handleCancel}
              width="682px"
            >
              <Table
                columns={this.resultColumns}
                dataSource={this.state.assignmentlist}
                pagination={false}
              />
            </Modal>
            {/* 绑定弹窗 */}
            <Modal
              title="请确认"
              visible={this.state.binding}
              onOk={() => {
                bindingOk();
              }}
              onCancel={bindingCancel}
            >
              <div>
                <div></div>
                <div>确认要{this.state.batch}</div>
              </div>
            </Modal>
          </div>
        </div>
      </>
    );
  }
  async fetchget() {
    try {
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {},
      });
      console.error(error);
    }
    let data = {
      pageIndex: this.state.page,
      pageSize: this.state.size,
      queryData: {
        commandKey: this.state.conditioncommand,
        terminalVal: this.state.conditionname,
      },
    };

    let res: any = await getresultsquery(data).catch((err) => {
      console.log(err);
    });
    const json: any = res;
    // this.setState({
    //   datalist:json.records,
    //   });
    // this.state.terminallist=json;
    // this.state.datalist=json.records;

    if (json.success) {
      this.setState({
        datalist: json.data.records,
        total: json.data.total,
      });
    }
  }
  namechange(e) {
    this.setState({
      conditionname: e.target.value,
    });
  }
  //任务详情
  async assignment() {
    let data = {
      id: this.state.id,
    };
    let res: any = await getassignment(data).catch((err) => {
      console.log(err);
    });
    const json: any = res;

    let records: any = json.data;

    if (json.success) {
      this.setState({
        assignmentlist: records,
      });
    }
  }
  commandchange(e) {
    this.setState({
      conditioncommand: e,
    });
  }

  //获取命令下拉
  async agreement() {
    let data = {
      code: "operateCommand",
    };
    let res: any = await getorderselect(data).catch((err) => {
      console.log(err);
    });
    const json: any = res;

    if (res) {
      this.setState({
        protocollist: json.data,
      });
    }
  }
  componentWillMount() {
    this.init();
  }
  init() {
    this.setState({ loading: true });
  }
}

export default Consequence;
